import COS from "cos-wx-sdk-v5"
import config from './config.js'
import store from './store.js'
export default {
	cos: {},

	// 初始化 cos
	initCos() {
		this.cos = new COS({
			SecretId: store.state.config.upload_set.cos_secretId,
			SecretKey: store.state.config.upload_set.cos_secretKey,
		});
	},
	// 文件上传
	update(file) {
		let files = file.split('.')
		let fileName = this.randomFileName(files[files.length-1])
		return new Promise((resolve,reject) => {
			this.cos.postObject({
				Bucket: store.state.config.upload_set.cos_bucket,
				Region: store.state.config.upload_set.cos_region,
				Key: fileName,
				FilePath: file,
				onProgress: function(info) {
					// console.log(JSON.stringify(info));
				}
			}, function(err, data) {
				resolve(err || data)
			});
		})
	},
	// 生成随机文件名
	randomFileName (suffix,num = 6) {
		let now = new Date()
		let fileName = '/common/'+ now.getFullYear() + (now.getMonth()+1 > 10 ? now.getMonth()+1 : '0' + (now.getMonth()+1)) + now.getDate() + '/'
		for (let i = 0; i < num; i++) {
			fileName += Math.floor(Math.random()*10)
		}
		return fileName + '.' + suffix
	}
}
